import { computed, defineComponent, provide, ref, watch, watchEffect } from 'vue'
import { RouterView } from 'vue-router'
import useAudio from 'hooks/useAudio'
import { MODE, playList as playListLocalStorage } from 'utils/play'
import { IMyMusic } from 'apis/types/business'
import { useStore } from 'vuex'

import { IAudioContext } from '@/store/modules/types'

export default defineComponent({
  name: '',
  setup() {
    const store = useStore()
    const playMode = computed(() => store.state.playMusic.playMode) // 播放顺序方式
    const musicId = computed(() => store.state.playMusic.musicId) // 歌曲ID

    const playList = ref<IMyMusic[]>(playListLocalStorage.getItem() || [])

    watch(musicId, () => {
      playList.value = playListLocalStorage.getItem()
    })

    const [audio, audioState, audioControls] = useAudio({
      autoplay: false,
      onEnded: () => playNextMusic(),
      onError: () => {
        if (playMode.value === MODE.SINGLE_CYCLE) {
          return
        }
        playNextMusic()
      },
    })
    const playMusic = (index: number) => {
      store.commit('play', {
        musicId: playList.value[index].id,
        music: playList.value[index],
      })
    }
    // 播放歌曲方式
    const playNextMusic = () => {
      console.log(playMode.value)
      switch (playMode.value) {
        case MODE.PLAY_IN_ORDER: {
          const list = playList.value
          const idx = list.findIndex(({ id }: IMyMusic) => id === musicId.value)
          if (list.length) {
            const nextIdx = idx > -1 ? (idx + 1) % list.length : 0
            playMusic(nextIdx)
          }
          return
        }
        case MODE.SINGLE_CYCLE: {
          audioControls.play()
          return
        }
        case MODE.SHUFFLE_PLAYBACK: {
          if (playList.value.length) {
            const randomIdx = Math.floor(Math.random() * playList.value.length)
            playMusic(randomIdx)
          }
          return
        }
        default:
          return
      }
    }
    provide('audioInfo', {
      audio,
      state: audioState,
      controls: audioControls,
    } as IAudioContext)

    return () => {
      return (
        <div>
          {audio}
          <RouterView />
        </div>
      )
    }
  },
})
